/*
 * @(#)BaseServer.java MinaNetSocket 2016年12月16日
 * Copyright (c) 2010-2020 Easy ITS, Inc. All rights reserved.
 */
package zhanglu.family.socket.serialization.server;

import java.net.InetSocketAddress;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

/**
 * 实例化服务端的管理类
 * 
 * @author zhanglu
 * @date 2016年12月16日
 */
public class BaseTCPServer {

    private IoHandlerAdapter handlerAction;     // 业务处理类

    private Integer          bufferSize = 2048; // 接收缓存区字节

    private Integer          idleTime   = 10;   // 连接超时时间

    private Integer          port;              // 服务端口

    /**
     * 实例化服务
     * 
     * @param handlerAction
     *            业务处理类
     * @param bufferSize
     *            接收缓存区字节 b
     * @param idleTime
     *            连接超时时间 毫秒
     * @param port
     *            服务端口
     */
    public BaseTCPServer(IoHandlerAdapter handlerAction, Integer bufferSize, Integer idleTime, Integer port) {
        this.handlerAction = handlerAction;
        this.bufferSize = bufferSize;
        this.idleTime = idleTime;
        this.port = port;
    }

    public boolean startServer() {
        // 服务器端的主要对象
        NioSocketAcceptor acceptor = new NioSocketAcceptor();
        DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();

        // 设置Filter链
        // acceptor.getFilterChain().addLast("logger", new LoggingFilter());

        // 设置消息处理类（创建、关闭Session，可读可写等等，继承自接口IoHandler）
        acceptor.setHandler(handlerAction);
        // 设置接收缓存区大小
        acceptor.getSessionConfig().setReadBufferSize(bufferSize);
        acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, idleTime);

        chain.addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
        try {
            // 服务器开始监听
            acceptor.bind(new InetSocketAddress(port));
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
